package com.broada.apm.logic.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.ajax.Result;
import com.broada.apm.base.BaseLogic;
import com.broada.apm.cache.AOManager;
import com.broada.apm.cache.L7ModuleCacheManager;
import com.broada.apm.entity.AO;
import com.broada.apm.entity.NoticeCommandException;
import com.broada.apm.entity.SSLCertificate;
import com.broada.apm.entity.Service;
import com.broada.apm.entity.ServiceLua;
import com.broada.apm.entity.convert.BeanConvert;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.indicator.api.common.ServiceNotExistException;
import com.broada.apm.logic.ServerLogic;
import com.broada.apm.model.Alert;
import com.broada.apm.model.Analyzer;
import com.broada.apm.model.L7Module;
import com.broada.apm.model.LuaSettings;
import com.broada.apm.model.ProtocolRelation;
import com.broada.apm.model.SettingItem;
import com.broada.apm.protocol.L7ModuleManager;
import com.broada.apm.protocol.ZeroClient;
import com.broada.apm.utils.ExceptionUtils;
import com.broada.apm.utils.IPUtils;
import com.broada.apm.utils.IdUtils;
import com.google.common.collect.Sets;

public class ServiceLogicImpl  extends BaseLogic implements ServerLogic {
	
	private static final int Cluster_Type = 2;
	private static final String NEXT_DIRECTION = "next";
	private static final String LAST_DIRECTION = "last";
	
	private Logger log = LoggerFactory.getLogger(ServiceLogicImpl.class);
	
	@Override
	public Service queryServiceById(String serviceId) {
		Service vo_server = new Service();
		com.broada.apm.model.Service service = null;
		if (serviceId.contains("-")) {
			service = serviceService.getServiceById(serviceId);
		} else {
			service = serviceService.getDisServiceById(serviceId);
		}
		if(service == null)
			return null;
		
		// data对象转front对象
		vo_server = (Service)BeanConvert.convertOjbect(service);
		// 手工指定的协议类型 前端未指定默认显示autoDiscoveryProtocol
		int protocolId = vo_server.getProtocol() > 0 ? vo_server.getProtocol() : vo_server.getAutoDiscoveryProtocol();
		L7Module l7Module = L7ModuleCacheManager.getInstance().get(String.valueOf(protocolId));
		vo_server.setProtocolName(l7Module != null ? l7Module.getName() : "TCP/UDP");
		
		return vo_server;
	}

	/**
	 * 通过关键字进行的模糊查询
	 */
	@Override
	public List<Service> queryDisServiceByKeyWord(String keyWord, String appId, String orderBy, boolean desc) {
		List<Service> servers = null;
		try {
			com.broada.apm.model.Service service = new com.broada.apm.model.Service();
			
			List<com.broada.apm.model.Service> services = null;
			if (StringUtils.isNotBlank(keyWord)) {
				service.setName(keyWord);// 通过业务组件名称模糊查询
				if (keyWord.contains(":") && StringUtils.isNumeric(keyWord.substring(keyWord.indexOf(":") + 1))) { // 通过IP+端口查询
					String[] keyWords = keyWord.split(":");
					if (keyWords.length >= 2) {
						service.setIp(keyWords[0]);
						service.setPort(Integer.parseInt(keyWords[1])); // port
					} else if (keyWords.length == 1) {
						service.setIp(keyWords[0]); // ip
					}
					services = serviceService.getDisServiceByCondition(service, orderBy, desc);
				} else if (StringUtils.isNumeric(keyWord) || keyWord.contains(".")) {// 通过端口或协议号或IP查询
					service.setIp(keyWord);
					if (StringUtils.isNumeric(keyWord)) {
						service.setPort(Integer.parseInt(keyWord));
						service.setProtocol(Integer.parseInt(keyWord));
						service.setAutoDiscoveryProtocol(Integer.parseInt(keyWord));
					}
					services = serviceService.getDisServiceByProtocal(service, orderBy, desc);
					// 考虑到8583协议，通过协议名称查询，考虑优化
					Map<String, com.broada.apm.model.Service> map = new HashMap<String, com.broada.apm.model.Service>();
					for (com.broada.apm.model.Service ser : services) {
						map.put(ser.getId(), ser);
					}
					services = new ArrayList<com.broada.apm.model.Service>();
					services = serviceService.getDisServiceByKeyWord(service, keyWord.toUpperCase(), orderBy, desc);
					for (com.broada.apm.model.Service ser : services) {
						map.put(ser.getId(), ser);
					}
					services = new ArrayList<com.broada.apm.model.Service>();
					for (String key : map.keySet()) {
						services.add(map.get(key));
					}
				} else {
					// 通过协议名称查询
					services = serviceService.getDisServiceByKeyWord(service, keyWord.toUpperCase(), orderBy, desc);
				}
			} else {
				services = serviceService.getDisServiceByProtocal(service, orderBy, desc);
			}
			servers = BeanConvert.convertService(services);
		} catch (Exception e) {
			ExceptionUtils.error(log, "查询节点列表失败", e);
		}
		return servers;
	}

	@Override
	public void deleteServiceById(String serviceId) {
		com.broada.apm.model.Service service = new com.broada.apm.model.Service();
		service.setId(serviceId);
		serviceService.deleteService(service);
		// 删除告警
		Alert alert = new Alert();
		alert.setServiceId(serviceId);
		alertService.deleteAlert(alert);
	}

	@Override
	public void deleteServiceByIds(String[] serviceIds) {
		for(String serviceId : serviceIds) {
			deleteServiceById(serviceId);
		}
	}

	@Override
	public void saveService(Service service) {
		serviceService.addService((com.broada.apm.model.Service)BeanConvert.convertFrontObjToDataObj(service));
	}

	@Override
	public void updateServiceName(Service service) throws ApmDataIndicatorException, ServiceNotExistException{
		com.broada.apm.model.Service ser = serviceService.getServiceById(service.getId());
		if (ser == null) {
			throw new ServiceNotExistException("参数错误,服务节点不存在！");
		}
		ser.setName(service.getName());
		serviceService.updateService(ser);
		AOManager.getInstance().put(ser.getId(), new AO(ser.getId(), service.getName()));

	}
	
	private void changeServiceName(String name, String ip, int port) throws Exception {
		if (StringUtils.isBlank(name) || StringUtils.isBlank(ip)) {
			throw new ApmDataIndicatorException("参数错误");
		}

		com.broada.apm.model.Service disService = serviceService.getDisServiceById(
				IdUtils.serviceId(com.broada.apm.model.Service.TCP, IPUtils.toLong(ip), port));
		if (disService == null) {
			throw new ServiceNotExistException("参数错误,服务节点不存在！");
		}

		AOManager.getInstance().put(disService.getId(), new AO(disService.getId(), name));
		disService.setName(name);
		serviceService.updateDisService(disService);
		
	}

	@Override
	public Service updateServiceProtocol(Service ser) throws ApmDataIndicatorException, NoticeCommandException {
		// 记录服务id 通知协议分析器
		String[] ids = null;
		com.broada.apm.model.Service service = null;
		if (ser.getId().contains("-")) {
			service = serviceService.getServiceById(ser.getId());
		} else {
			service = serviceService.getDisServiceById(ser.getId());
		}
		service.setProtocol(ser.getProtocol());
		ids = new String[1];
		ids[0] = ser.getId();
		L7ModuleManager.setL7Module(ser.getProtocol(), ids);
		// 与应用无关
		serviceService.updateDisService(service);
		return (Service) BeanConvert.convertOjbect(service);
	}

	@Override
	public void deleteDiscoveryService(String id) throws Exception {
		try {
			com.broada.apm.model.Service service = serviceService.getDisServiceById(id);
			// 删除上下级业务组件关系
			List<ProtocolRelation> relations = relationService.getDisRelationByService(service);
			for (ProtocolRelation nr : relations) {
				relationService.deleteDisRelation(nr);;
			}
			// 删除应用topo
			List<com.broada.apm.model.Service> appService = serviceService.getTopoServiceBySerivceId(id);
			for (com.broada.apm.model.Service as : appService) {
				serviceService.deleteService(as);
				// 删除告警
				Alert alert = new Alert();
				alert.setServiceId(as.getId());
				alertService.deleteAlert(alert);
			}
			// 删除节点
			serviceService.deleteDiscoveryService(service);
		} catch (Exception e) {
			log.error("删除手动添加业务节点失败", e);
			throw new Exception(e.getMessage());
		}
	}

	@Override
	public List<Service> queryDisServiceByCondition(String keyWord,
			String serviceId, String direction, String appId, String orderBy, boolean desc) {
		List<Service> vo_servers = new ArrayList<Service>();
		List<Service> services = null;
		String[] appNodeIds = new String[0];
		com.broada.apm.model.ApplicationSystem app = null;
		if (StringUtils.isNotBlank(appId)) {
			app = applicationService.getApplicationWithServiceAndRelById(appId);
			if (app != null) {
				appNodeIds = app.getServiceIds();
			} else {
				return vo_servers;
			}
		}
		if (LAST_DIRECTION.equals(direction)) {
			services = queryLastService(serviceId, appId);
			if (services != null) {
				for (Service ser : services) {
					ser.setNext(serviceId);
				}
			}
		} else if (NEXT_DIRECTION.equals(direction)) {
			services = queryNextService(serviceId);
			if (services != null) {
				for (Service ser : services) {
					ser.setPrevious(serviceId);
				} 
			}
		} else {
			services = queryDisServiceByKeyWord(keyWord, appId, orderBy, desc);
		}
		if (services == null || services.isEmpty())
			return vo_servers;
		// 过滤服务节点，设置协议名称
		for (Service serv : services) {
			// 如果service不是应用的topo节点，则保留
			if (!ArrayUtils.contains(appNodeIds, IdUtils.serviceIdWithApp(appId, serv.getId()))) {
				int protocolId = serv.getProtocol() > 0 ? serv.getProtocol() : serv.getAutoDiscoveryProtocol();
				if (protocolId == 1 && StringUtils.isNotBlank(keyWord) && (keyWord.toUpperCase().contains("S") || keyWord.toUpperCase().contains("Y")
						|| keyWord.toUpperCase().contains("N") || keyWord.toUpperCase().contains("M") || keyWord.toUpperCase().contains("O") || keyWord.toUpperCase().contains("L")
						|| keyWord.toUpperCase().contains("E"))) continue;

				L7Module l7Module = L7ModuleCacheManager.getInstance().get(String.valueOf(protocolId));
				serv.setProtocolName(l7Module == null || protocolId == 1  ? "TCP/UDP" : l7Module.getName());
				vo_servers.add(serv);
			}
		}
		return vo_servers;
	}

	@Override
	public List<Service> queryNextService(String serviceId) {
		List<Service> nextProtocols = new ArrayList<Service>();
		try {
			com.broada.apm.model.Service server = serviceService.getServiceById(serviceId);
			if (server != null) {
				Long[] ipNums;
				if (server.getNodeType() == Cluster_Type) {
					List<com.broada.apm.model.Service> servers = serviceService.getChildServiceByClusterId(serviceId); 
					if (servers == null || servers.size() == 0)
						return null;
					Set<Long> ipNumSet = Sets.newHashSet();
					for (com.broada.apm.model.Service s : servers) {
						ipNumSet.add(s.getIpNum());
					}
					ipNums = ipNumSet.toArray(new Long[] {});
				} else {
					ipNums = new Long[1];
					ipNums[0] = server.getIpNum();
				}
				
				List<ProtocolRelation> relations = new ArrayList<ProtocolRelation>();
				for(int i = 0; i < ipNums.length; i++) {
					List<ProtocolRelation> disRelations = relationService.getDisRelationBySrcIp(ipNums[i]);
					relations.addAll(disRelations);
				}
				if (relations == null || relations.isEmpty())
					return null;
				for (ProtocolRelation r : relations) {
					Service serivce = queryDisServiceById(r.getServiceId());
					if(serivce != null)
						nextProtocols.add(serivce);
				}
			}
		} catch (Exception e) {
			ExceptionUtils.error(log, "查询后续节点失败", e);
		}
		return nextProtocols;
	}

	@Override
	public List<Service> queryLastService(String serviceId, String appId) {
		List<Service> lastProtocols = new ArrayList<Service>();
		try {
			com.broada.apm.model.Service server = serviceService.getServiceById(serviceId);
			if (server != null) {
				String[] ids;
				if (server.getNodeType() == Cluster_Type) {
					List<com.broada.apm.model.Service> servers = serviceService.getChildServiceByClusterId(serviceId); 
					if (servers == null || servers.size() == 0)
						return null;
					ids = new String[servers.size()];
					for (int i = 0; i < servers.size(); i++) {
						ids[i] = IdUtils.serviceId(appId, servers.get(i).getId());
					}
				} else {
					ids = new String[1];
					ids[0] = IdUtils.serviceId(appId, server.getId());
				}
				List<ProtocolRelation> relations = new ArrayList<ProtocolRelation>();
				for(int i = 0; i < ids.length; i++) {
					List<ProtocolRelation> disRelations = relationService.getDisRelationByServiceId(ids[i]);
					relations.addAll(disRelations);
				}
				if (relations == null || relations.isEmpty())
					return null;
				for (ProtocolRelation r : relations) {
					List<Service> services = queryDisServiceByIpNum(r.getSrcIp());
					if(services != null)
						lastProtocols.addAll(services);
				}
			}
		} catch (Exception e) {
			ExceptionUtils.error(log, "查询前置节点失败", e);
		}
		return lastProtocols;
	}

	public List<Service> queryDisServiceByIpNum(long ipNum) {
		List<com.broada.apm.model.Service> services = serviceService.getDisServiceByIpNum(ipNum);
		return BeanConvert.convertService(services);
	}

	@Override
	public List<Service> queryServiceByAppId(String appId) {
		List<com.broada.apm.model.Service> services = serviceService.getServicesByAppId(appId);
		List<Service> sers = BeanConvert.convertService(services);
		setServiceProtocolName(sers);
		return sers;
	}

	@Override
	public void updateService(Service service) {
		com.broada.apm.model.Service ser = (com.broada.apm.model.Service)BeanConvert.convertFrontObjToDataObj(service);
		serviceService.updateService(ser);
	}

	@Override
	public List<Service> queryChildServiceByApplicationId(String clusterId) {
		List<com.broada.apm.model.Service> services = serviceService.getChildServiceByClusterId(clusterId);
		return BeanConvert.convertService(services);
	}

	@Override
	public void saveDisService(Service service) {
		serviceService.addDisService((com.broada.apm.model.Service)BeanConvert.convertFrontObjToDataObj(service));
	}

	@Override
	public void updateDisService(Service disService) {
		serviceService.updateDisService((com.broada.apm.model.Service)BeanConvert.convertFrontObjToDataObj(disService));
	}

	@Override
	public Service queryDisServiceById(String serviceId) {
		com.broada.apm.model.Service service = serviceService.getDisServiceById(serviceId);
		return (Service) BeanConvert.convertOjbect(service);
	}

	@Override
	public List<Service> queryDisServiceByIpAndPort(String ip, int port) {
		List<com.broada.apm.model.Service> services = serviceService.getDisServiceByIpAndPort(ip == null ? "" : ip, port);
		List<Service> sers = BeanConvert.convertService(services);
		setServiceProtocolName(sers);
		return sers;
	}

	@Override
	public List<Service> queryServicesByIds(String[] serviceIds) {
		List<com.broada.apm.model.Service> services = new ArrayList<com.broada.apm.model.Service>();
		for(String serviceId : serviceIds) {
			com.broada.apm.model.Service service = serviceService.getServiceById(serviceId);
			services.add(service);
		}
		List<Service> sers = BeanConvert.convertService(services);
		setServiceProtocolName(sers);
		return sers;
	}

	private void setServiceProtocolName(List<Service> services) {
		for (Service serv : services) {
			int protocolId = serv.getProtocol() > 0 ? serv.getProtocol() : serv.getAutoDiscoveryProtocol();
			L7Module l7Module = L7ModuleCacheManager.getInstance().get(String.valueOf(protocolId));
			serv.setProtocolName(l7Module != null ? l7Module.getName() : "TCP/UDP");
		}
	}

	@Override
	public void updateServiceLua(Service service) throws Exception {
		List<String> serviceIds = new ArrayList<String>();
		com.broada.apm.model.Service services = null;
//		if(service.getId().contains("-")){
//			// 应用节点设置lua
//			services = serviceService.getServiceById(service.getId());
//		}else{
//			// 服务节点设置lua
//			services = serviceService.getDisServiceById(service.getId());
//		}
		services = serviceService.getDisServiceById(service.getId());
		if(services != null ){
			if(services.getNodeType() == com.broada.apm.model.Service.NodeTypeCluster){
				// 集群节点
				String[] nodeIds = services.getNodeIds();
				for(String id : nodeIds){
					serviceIds.add(id);
				}
			} else{
				// 非集群节点
				serviceIds.add(services.getId());
			}
		} else{
			throw new ServiceNotExistException("参数错误,服务节点不存在！");
		}
		for(String serviceId : serviceIds){
			String _serviceId = serviceId.substring(serviceId.lastIndexOf("-") + 1, serviceId.length());
			com.broada.apm.model.Service ser = serviceService.getDisServiceById(_serviceId);
			if (ser == null) {
				throw new ServiceNotExistException("参数错误,服务节点不存在！");
			}
			// 不论是单个节点还是集群，都会设置lua
			ser.setLua(service.getLua());
			// 通知协议分析器端
			List<Analyzer> analyzers = analyzerService.getAllAnalyzerNoPage();
			if(analyzers != null && analyzers.size() > 0){
				for(Analyzer analyzer:analyzers){
					try (ZeroClient client = new ZeroClient()) {
						String server_add = "tcp://" + analyzer.getIp() + ":" + analyzer.getPort();
						client.connect(server_add);
						client.lua_setup(IPUtils.toLittleEndianInteger(ser.getIp()), ser.getPort(), ser.getLua());
						client.commit();
						client.close();
					} catch (Exception e) {
						ExceptionUtils.error(log, "通知" + analyzer.getName() + "协议分析器端异常", e);
						throw e;
					}
				}
			}
			serviceService.updateDisServiceLua(ser);
		}
	}

	@Override
	public void saveSSLCertificate(SSLCertificate sslCertificate) throws Exception {
		com.broada.apm.model.SSLCertificate ssl = serviceService.getSSLBySericeId(sslCertificate.getServiceId());
		
		// 根据serviceId查询库中是否已存在对应的记录，没有则新增，有则更新
		try {
			if (ssl == null) {
				ssl = new com.broada.apm.model.SSLCertificate();
				BeanConvert.copyBean(ssl, sslCertificate);
				serviceService.addSSLCertificate(ssl);
			} else {
				ssl.setServiceId(sslCertificate.getServiceId());
				ssl.setSslType(sslCertificate.getSslType());
				ssl.setSslPwd(sslCertificate.getSslPwd());
				ssl.setPrivateKey(sslCertificate.getPrivateKey());
				serviceService.updateSSLCertificate(ssl);
			}
		} catch (Exception e) {
			throw new Exception("SSL证书设定异常");
		}
		
	}

	@Override
	public SSLCertificate querySSLByServiceId(String serviceId) throws Exception {
		SSLCertificate vo_sslCertificate = new SSLCertificate();
		com.broada.apm.model.SSLCertificate sslCertificate = serviceService.getSSLBySericeId(serviceId);
		// 如果没设定SSL证书， 则返回null
		if (sslCertificate == null) {
			return null;
		}
		// data对象转front对象
		BeanConvert.copyBean(vo_sslCertificate, sslCertificate);
		return vo_sslCertificate;
	}

	@Override
	public void deleteSSLCertificate(String serviceId) {
		com.broada.apm.model.SSLCertificate sslCertificate = new com.broada.apm.model.SSLCertificate();
		sslCertificate.setServiceId(serviceId);
		serviceService.deleteSSLCertificate(sslCertificate);
	}

	@Override
	public ServiceLua queryLuaScriptByServiceId(String serviceId) throws Exception {
		ServiceLua vo_lua = new ServiceLua();
		com.broada.apm.model.Service service = null;
		if (serviceId.contains("-")) {
			service = serviceService.getServiceById(serviceId);
		} else {
			service = serviceService.getDisServiceById(serviceId);
		}
		if(service.getNodeType() != com.broada.apm.model.Service.NodeTypeCluster){
			// 非集群节点
			String _serviceId = serviceId.substring(serviceId.lastIndexOf("-") + 1, serviceId.length());
			service = serviceService.getDisServiceById(_serviceId);
		}
		if (service == null) {
			throw new ServiceNotExistException("参数错误,服务节点不存在！");
		}
		// 如果没设定lua脚本， 则返回null
		String lua = service.getLua();
		if (StringUtils.isBlank(lua)) {
			return null;
		}
		if (lua.contains("/\n")) {
			lua = lua.replace("/\n", "<br/>");
		}
		vo_lua.setServiceId(serviceId);
		vo_lua.setLua(lua);
		return vo_lua;
	}

	@Override
	public Service getAppServiceByIpAndPort(String appId, String ip, int port) {
		com.broada.apm.model.Service service = serviceService.getAppServiceByIpAndPort(appId, ip, port);
		return (Service) BeanConvert.convertOjbect(service);
	}

	@Override
	public Map<String, Object> queryServiceFocusCount() throws Exception {
		Map<String, Object> serviceMap = new HashMap<String, Object>();

		int focusCount = serviceService.getServiceCount(1);
		int serviceAll = serviceService.getServiceCount(0);
		serviceMap.put("serviceFocus", focusCount);
		serviceMap.put("serviceAll", serviceAll);

		return serviceMap;
	}

	@Override
	public void setServiceName(Service service) throws Exception {
		changeServiceName(service.getName(), service.getIp(), service.getPort());
	}

	@Override
	public List<Service> getDisServiceFocusOrNot(Service service, String serviceType, String sortByMysql, boolean desc, int pageSize, int pageIndex, int serverity, Date startDate, Date endDate) {
		com.broada.apm.model.Service ser = new com.broada.apm.model.Service();
		ser = (com.broada.apm.model.Service) BeanConvert.convertFrontObjToDataObj(service);
		List<com.broada.apm.model.Service> serviceList = serviceService.getDisServiceFocusOrNot(ser, serviceType, sortByMysql, desc, pageSize, pageIndex, serverity, startDate, endDate);
		List<Service> list = BeanConvert.convertService(serviceList);
		return list;
	}

	@Override
	public Service updateServiceIps(String appId, Service service) throws Exception {
		com.broada.apm.model.Service ser = serviceService.getServiceById(service.getId());
		if (ser == null) {
			throw new ServiceNotExistException("参数错误,服务节点不存在！");
		}
		ser.setFilterIps(service.getFilterIps());
		try {
			serviceService.updateService(ser);
			indicatorService.NoticeCommand("reload", "app", appId);
		} catch (NoticeCommandException e) {
			ExceptionUtils.error(log, "通知Indicator模块异常", e);
			throw e;
		}
		return (Service) BeanConvert.convertOjbect(ser);
	}

	@Override
	public Result saveLuaSettings(LuaSettings settings){
		Result result = new Result();
		try{
			String lua = generateLuaScript(settings.getThresType(), settings);
			// 通知协议器
			com.broada.apm.model.Service ser = serviceService.getDisServiceById(settings.getServiceId());
			// 通知协议分析器端
			List<Analyzer> analyzers = analyzerService.getAllAnalyzerNoPage();
			if(analyzers != null && analyzers.size() > 0){
				for(Analyzer analyzer:analyzers){
					try (ZeroClient client = new ZeroClient()) {
						String server_add = "tcp://" + analyzer.getIp() + ":" + analyzer.getPort();
						client.connect(server_add);
						client.lua_setup(IPUtils.toLittleEndianInteger(ser.getIp()), ser.getPort(), lua);
						client.commit();
						client.close();
					} catch (Exception e) {
						ExceptionUtils.error(log, "通知" + analyzer.getName() + "协议分析器端异常", e);
						throw e;
					}
				}
			}
			// 保存节点lua
			com.broada.apm.model.Service service = new com.broada.apm.model.Service();
			service.setId(settings.getServiceId());
			service.setLua(lua);
			serviceService.updateDisServiceLua(service);
			// 保存动态配置脚本信息
			luaSettingsService.saveLuaSettings(settings);
		}catch(Exception e){
			result.setFailMessage("动态配置lua脚本失败");
		}
		return result;
	}

	@Override
	public Result queryLuaSettings(String serviceId) {
		Result result = new Result();
		try{
			LuaSettings settings = luaSettingsService.queryLuaSettings(serviceId);
			result.put("settings", settings);
		}catch(Exception e){
			result.setFailMessage("查询动态配置lua脚本失败");
		}
		return result;
	}
	
	/** 
	 * 生成完整lua脚本
	 * @param type
	 */
	private String generateLuaScript(String type, LuaSettings settings){
		StringBuilder lua_head = new StringBuilder("");
		StringBuilder lua_content = new StringBuilder("");
		if(settings.getItems() == null || StringUtils.isBlank(settings.getL7Field())){
			return "";
		}
		if(type.equals("xml")){  //xml
			lua_head = new StringBuilder("#!/usr/bin/lua\nrequire (\"apm_core\");\n"
					+ "function post_analysis() \n"
					+ "\t local ApmData = require(\"ApmData\"); \n"
					+ "\t local xml = require(\"ApmXml\"); \n"
					+ "\t local xml_text = ApmData.getField(\"" + settings.getL7Field() + "\", 1); \n"
					+ "\t if xml_text ~= nil then \n"
					+ "\t \t local xml_doc = xml.load(xml_text); \n");
			for(SettingItem item:settings.getItems()){
				if(StringUtils.isBlank(item.getPath())){
					continue;
				}
				lua_content.append("\t \t local xml_field_value = xml.getValue(xml_doc, \"" + item.getPath() +"\"); \n"
						+ "\t \t if xml_field_value ~= nil then \n"
						+ "\t \t \t ApmData.replaceField(\"" + item.getFieldName() + "\",xml_field_value);\n"
						+ "\t \t end \n");
			}
			lua_content.append("\t end \nreturn; \nend");
		}else{  //json
			lua_head = lua_head.append("#!/usr/bin/lua\nrequire (\"apm_core\");\n"
					+ "function post_analysis()\n"
					+ "\t local ApmData = require(\"ApmData\");\n"
					+ "\t local json = require(\"ApmJson\");\n"
					+ "\t local s_value;\n"
					+ "\t local json_table;\n"
					+ "\t local json_text;\n"
					+ "\t json_text = ApmData.getField(\"" + settings.getL7Field() + "\", 1); \n"
					+ "\t if json_text ~= nil  then \n"
					+ "\t \t json_table = json.decode(json_text);\n"
					+ "\t \t if  json_table ~= nil  then\n");
			for(SettingItem item:settings.getItems()){
				if(StringUtils.isBlank(item.getPath())){
					continue;
				}
				lua_content = lua_content.append("\t \t \t s_value = json_table[\""+ item.getPath() +"\"];\n"
						+ "\t \t \t if  s_value ~= nil then\n"
						+ "\t \t \t \t  ApmData.replaceField(\"" + item.getFieldName() + "\", \"" + item.getPath() + "\")\n"
						+ "\t \t \t end\n");
			}
			lua_content.append("\t \t end\n\t end\nreturn;\nend");
		}
		return lua_head.toString() + lua_content.toString();
	}
}
